<template>
  <div class="update-photo">
    <img :src="image" alt="" class="img" ref="img">
    <van-nav-bar
      left-text="返回"
      right-text="完成"
      class="bottomBar"
      @click-left="$emit('close')"
      @click-right="finish"
    />
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { updateUserPhoto } from '@/apis/user'
export default {
  name: 'UpdatePhoto',
  props: {
    file: {
      required: true
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  mounted () {
    this.initCropper()
  },
  methods: {
    initCropper () {
      let cropper = new Cropper(this.$refs.img, {
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        cropBoxMovable: false,
        cropBoxResizable: false,
        background: false,
        movable: true
      })
      this.cropper = cropper
    },
    finish () {
      this.$toast.loading({
        message: '上传中',
        forbidClick: true,
        duration: 0
      })
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        let fd = new FormData()
        fd.append('photo', blob)
        await updateUserPhoto(fd)
        this.$toast.success('保存成功')
        this.$emit('update-photo', window.URL.createObjectURL(blob))
        this.$emit('close')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.bottomBar{
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #000;
}
.img{
  max-width: 100%;
  display: block;
}
</style>
